package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.CommentRespository;
import model.UserRepository;
import myBeans.Comment;

/**
 * Servlet implementation class CommentServlet
 */
@WebServlet("/CommentServlet")
public class CommentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CommentServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/html");

		ServletContext ctx = getServletContext();
		Connection conn = (Connection) ctx.getAttribute("connection");

		String nextJSP = "/ResultPage.jsp";
		System.out.println("nextJSP : " + nextJSP);
		RequestDispatcher rd = request.getRequestDispatcher(nextJSP);
		request.setAttribute("pageName", "Share With Me");

		if (conn != null) {
			if (request.getParameter("shareButton") != null) {// click
																// shareButton
				try {
					CommentRespository acomment = new CommentRespository(conn);

					String sharegroupid = acomment
							.GetShareGroupIdFrompageCall(request
									.getParameter("page_call"));
					int sharetypeid = 2; // comment (tbsharetype)
					int sharevalue = Integer.parseInt(request
							.getParameter("worm"));
					String isbn = request.getParameter("isbn");

					// check comment cannot null
					if (request.getParameter("comment") == null) {
						request.setAttribute("destinationUrl",
								request.getContextPath()
										+ "/ShareWithMe_detail.jsp?bisbn="
										+ isbn);
						request.setAttribute("Message",
								"Please Share Something With Us");
						System.out.println("Please Share Something With Us");
						rd.forward(request, response);
					}
					String sharecomment = request.getParameter("comment");

					// get userId
					UserRepository getName = new UserRepository();
					String userid = getName.getUserIDFromDisplayName(request
							.getParameter("userId"));

					if (acomment.pageShareWithMeComment(new Comment(
							sharegroupid, sharetypeid, sharevalue,
							sharecomment, userid, isbn, ""))) {
						// done
						System.out.println("share comment done");
						response.sendRedirect(request.getContextPath()
								+ "/ShareWithMe_detail.jsp?bisbn=" + isbn);
					} else {
						// cannot insert data
						request.setAttribute("destinationUrl",
								request.getContextPath()
										+ "/ShareWithMe_detail.jsp?bisbn="
										+ isbn);
						request.setAttribute("Message", "cannot share comment");
						System.out.println("cannot share comment");
						rd.forward(request, response);
					}
				} catch (NamingException e) {
					System.out.println("NamingException CommentServlet : "
							+ e.getMessage());
					e.printStackTrace();
				} catch (SQLException e) {
					System.out.println("SQLException CommentServlet : "
							+ e.getMessage());
					e.printStackTrace();
				}
			}  else if (request.getParameter("voteButton") != null) {
				try {
					CommentRespository objVote = new CommentRespository(conn);
					CommentRespository alike = new CommentRespository(conn);
					String sharegroupid = alike
							.GetShareGroupIdFrompageCall(request
									.getParameter("page_call"));
					int sharetypeid = 3;
					int sharevalue = Integer.parseInt(request
							.getParameter("ratePoint"));
					// get userId
					UserRepository getName;
					getName = new UserRepository();
					String userid = getName.getUserIDFromDisplayName(request
							.getParameter("userId"));
					String isbn = request.getParameter("isbn");
					System.out.println("voteButton : "+sharegroupid +"," +sharetypeid+", " +
							sharevalue+", " + userid+", " + isbn+ "/");
					if(objVote.giveARate(new Comment(sharegroupid, sharetypeid,
							sharevalue, "", userid, isbn, ""))){
						response.sendRedirect(request.getContextPath()
								+ "/ShareWithMe_detail.jsp?bisbn="
								+ request.getParameter("isbn"));
					}else {
						// cannot insert data
						System.out.println("cannot vote");
						request.setAttribute("destinationUrl",
								request.getContextPath()
										+ "/ShareWithMe_detail.jsp?bisbn="
										+ isbn);
						request.setAttribute("Message",
								"cannot vote");
						rd.forward(request, response);
					}
				} catch (NamingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else if (request.getParameter("WormButton") != null) { // click
																		// worm
																		// image

				try {
					CommentRespository alike = new CommentRespository(conn);
					String sharegroupid = alike
							.GetShareGroupIdFrompageCall(request
									.getParameter("page_call"));
					int sharetypeid = 1; // like (tbsharetype)
					int sharevalue = Integer.parseInt(request
							.getParameter("WormButton"));
					// get userId
					UserRepository getName;
					getName = new UserRepository();
					String userid = getName.getUserIDFromDisplayName(request
							.getParameter("userId"));
					String isbn = request.getParameter("isbn");

					// check allow befor like
					Comment usercomment = new Comment(sharegroupid,
							sharetypeid, sharevalue, "", userid, isbn, "");
					if (alike.checkLikeAllowed(usercomment) && !userid.isEmpty()) {// no record for
																// this user

						if (alike.likeWorm(usercomment)) {
							// done
							System.out.println("share like done");
							response.sendRedirect(request.getContextPath()
									+ "/ShareWithMe_detail.jsp?bisbn=" + isbn);
						} else {
							// cannot insert data
							System.out.println("cannot like comment");
							request.setAttribute("destinationUrl",
									request.getContextPath()
											+ "/ShareWithMe_detail.jsp?bisbn="
											+ isbn);
							request.setAttribute("Message",
									"cannot like comment");
							rd.forward(request, response);
						}
					} else {
						System.out
								.println("CommentServlet : not allow user to like a worm");
						request.setAttribute("destinationUrl",
								request.getContextPath()
										+ "/ShareWithMe_detail.jsp?bisbn="
										+ request.getParameter("isbn"));
						request.setAttribute("Message", "not allow user "
								+ request.getParameter("userId")
								+ " to like a worm");
						rd.forward(request, response);
					}
				} catch (NamingException e) {
					System.out.println("NamingException CommentServlet : "
							+ e.getMessage());
					e.printStackTrace();
				} catch (SQLException e) {
					System.out.println("SQLException CommentServlet : "
							+ e.getMessage());
					e.printStackTrace();
				}
			} else {
				System.out.println("CommentServlet : button not pass value");
				request.setAttribute(
						"destinationUrl",
						request.getContextPath()
								+ "/ShareWithMe_detail.jsp?bisbn="
								+ request.getParameter("isbn"));
				request.setAttribute("Message", "cannot like comment");
				System.out.println("button not pass value");
				rd.forward(request, response);
				// response.sendRedirect(request.getContextPath()
				// + "/ShareWithMe_detail.jsp?bisbn="
				// + request.getParameter("isbn"));
			}
		} else {
			System.out.println("No DataBase connection");
			// out.print("No DataBase connection");
			request.setAttribute("destinationUrl",
					request.getContextPath() + "/ShareWithMe_detail.jsp?bisbn="
							+ request.getParameter("isbn"));
			request.setAttribute("Message", "No DataBase connection");
			rd.forward(request, response);
		}

	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
